import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import { getConversationList } from '@/api/modules/message.js';
import { httpToHttps } from '@/utils/handle.js';

const SDKAppID = 1600069105;  // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID

import {
  getUserInfo,
  // getLoginInfo,
  initUserInfo,
} from "../api/index";
// import MD5 from "./md5.js";

export default class IMEventHandler {
  constructor(callback) {
    this.callback = callback;
    this.getUserInfo();
    return this;
  }
  getUserInfo() {
    let personId = uni.getStorageSync("person-id").slice(2) || undefined;
    if (!personId) return
    let uname = personId;
    if (uni.getStorageSync("login-status") === "consultant") {
      uname += `_consultant`;
    }
    let param = {
      uname: uname,
    };

    // 初始化用户信息，返回 userSig
    initUserInfo(param).then((res) => {
      if (res && +res.code === 200) {
        // this.getLoginInfo();
        res.data.pic = httpToHttps(res.data.pic);
        getApp().globalData.imInfo = res.data;
        // getApp().globalData.imInfo.username = personId;
        // getApp().globalData.imInfo.info.extras = {
        //   Get_Person_Iname: res.info.nick,
        //   GET_PIC: res.info.pic,
        // };

        this.init(res.data);

      }
    });
  }
  // getLoginInfo() {
  //   let personId = uni.getStorageSync("person-id").slice(2) || undefined;
  //   let param = {
  //     pid: personId,
  //   };
  //   getLoginInfo(param).then((res) => {
  //     // console.log('loginInfo', res)
  //     if (res && +res.code === 200) {

  //       if (uni.getStorageSync("login-status") === "consultant") {
  //         personId += `_consultant`;
  //       }
  //       getApp().globalData.imInfo.username = personId;
  //       getApp().globalData.imInfo.info.extras = {
  //         Get_Person_Iname: res.info.nick,
  //         GET_PIC: res.info.pic,
  //       };

  //       this.init(res.info);
  //       getApp().globalData.imAccount = res.info;
  //     }
  //   });
  // }
  // 注册
  register() {
    let personId = uni.getStorageSync("person-id").slice(2) || undefined;
    let param = {
      uname: personId,
    };
    initUserInfo(param).then((res) => {
      if (res && +res.code === 200) {
        this.getUserInfo();
      }
    });
  }
  // 初始化
  init(data) {
    var that = this;
    if (!getApp().globalData.tim) {

      let chat = TencentCloudChat.create({
          SDKAppID
      }); // SDK 实例通常用 chat 表示
      // chat.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
      chat.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
      // 注册腾讯云即时通信 IM 上传插件
      chat.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});

      getApp().globalData.tim = chat;
    }

    that.login(data.uname, data.userSig);

    // getApp()
    //   .globalData.tim.init({
    //     appkey: data.appKey,
    //     random_str: data.random_str,
    //     signature: data.signature,
    //     timestamp: data.timestamp,
    //     flag: 1,
    //   })
    //   .onSuccess(function (res) {
    //     // console.log("onInit", new Date().getTime());
    //     that.login(data.pid, data.pwd);
    //   })
    //   .onFail(function () {
    //     // console.log(JSON.stringify(data));
    //   });
  }
  //登录
  async login(userID, userSig) {
    var that = this;
    let personId = userID;
    let chat = getApp().globalData.tim;
    if (uni.getStorageSync("login-status") === "consultant") {
      console.log("是个顾问!", uni.getStorageSync("login-status"));
      personId += `_consultant`;
    }
    if (!chat) {
      this.getUserInfo();
      return;
    }
    let promise = chat.login({ userID: personId, userSig });
    promise.then(function(imResponse) {
      console.log(imResponse.data); // 登录成功
      if (imResponse.data.repeatLogin === true) {
        // 标识账号已登录，本次登录操作为重复登录。
        console.log(imResponse.data.errorInfo);
      }

      getApp().globalData.bus.$emit("LOGIN_SUCCESS");
      that.eventListen();
    }).catch(function(imError) {
      console.warn('login error:', imError); // 登录失败的相关信息
      getApp().globalData.bus.$emit("LOGIN_ERROR", imError);
    });
    
  }

  // 处理会话列表
  handleConversation(conversationList) {
    console.log("conversationList：",conversationList)
    let conversationListOld = getApp().globalData.conversationList || [];
    if (conversationList.length === 0) {
      // 如果新列表为空，直接使用旧列表
      conversationList = conversationListOld;
    } else {
      let map = {};
      conversationListOld.forEach((itemOld) => {
        map[itemOld.conversationID] = itemOld;
      })

      conversationList.forEach((item) => {
        if (map[item.conversationID]) {
          if (!item.conversationId) {
            map[item.conversationID] = {...map[item.conversationID], ...item};
          }
          map[item.conversationID].unreadCount = item.unreadCount;
        } else {
          map[item.conversationID] = item;
        }
      })
      conversationList = Object.values(map);
    }

    // let unreadCnt = 0;
    // if (conversationList) {
    //   conversationList.forEach((item) => {
    //     unreadCnt += item.unreadCount;
    //   });
    // }
    // getApp().globalData.msgUnreadCnt = unreadCnt;
    getApp().globalData.conversationList = conversationList;
    getApp().globalData.bus.$emit("UPDATE_CONVERSATION");
  }

  onSdkReady (event) {
    setTimeout(() => {
      this.getConversation();
    }, 2000);
  }

  onMessageReceived(event) {
    console.log("onMessageReceived : " , event.data);
    getApp().globalData.bus.$emit("RECEIVE_CHATING_MESSAGE", event.data);
  }

  onConversationListUpdated(event) {
    console.log('CONVERSATION_LIST_UPDATED：',event.data); // 包含 Conversation 实例的数组
    // Conversation 数据结构详情请参考 https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Conversation.html
    this.handleConversation(event.data, 'update');
  };

  onTotalUnreadMessageCountUpdated(event) {
    console.log('TOTAL_UNREAD_MESSAGE_COUNT_UPDATED：',event.data); // 当前单聊和群聊会话的未读总数
    getApp().globalData.msgUnreadCnt = event.data;
  };

  onKickedOut (event) {
    console.log(event.data.type);
    // TencentCloudChat.TYPES.KICKED_OUT_MULT_ACCOUNT(Web端，同一账号，多页面登录被踢)
    // TencentCloudChat.TYPES.KICKED_OUT_MULT_DEVICE(同一账号，多端登录被踢)
    // TencentCloudChat.TYPES.KICKED_OUT_USERSIG_EXPIRED(签名过期)
    // TencentCloudChat.TYPES.KICKED_OUT_REST_API(REST API kick 接口踢出)
    if (event.data.type == TencentCloudChat.TYPES.KICKED_OUT_MULT_ACCOUNT) {
      getApp().globalData.tim && getApp().globalData.tim.logout();
      getApp().globalData.tim = null;
    }
  };

  onNetStateChange(event) {
    // event.data.state 当前网络状态，枚举值及说明如下：
    // TencentCloudChat.TYPES.NET_STATE_CONNECTED - 已接入网络
    // TencentCloudChat.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动，SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
    // TencentCloudChat.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息
    console.log("onDisconnect 连接断了！");
    if (event.data.state == TencentCloudChat.TYPES.NET_STATE_DISCONNECTED) {
      uni.showToast({
        icon: "none",
        title: "当前网络不可用, 正在重试",
        duration: "60000",
      });
    }
  };

  onMessageReadByPeer(event) {
    // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isPeerRead 属性值为 true
    console.log("onMessageReadByPeer 已读消息：", event.data);
    getApp().globalData.bus.$emit("MESSAGE_READ_BY_PEER", event.data);
  };

  //事件监听
  eventListen() {
    var that = this;
    let chat = getApp().globalData.tim;

    chat.off(TencentCloudChat.EVENT.SDK_READY, this.onSdkReady);
    chat.on(TencentCloudChat.EVENT.SDK_READY, this.onSdkReady, this);

    chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
    chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.onMessageReceived, this);

    // 会话列表更新
    chat.off(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
    chat.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated, this);

    // 会话未读总数更新
    chat.off(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, this.onTotalUnreadMessageCountUpdated);
    chat.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, this.onTotalUnreadMessageCountUpdated, this);

    // 用户被踢下线时触发
    chat.off(TencentCloudChat.EVENT.KICKED_OUT, this.onKickedOut);
    chat.on(TencentCloudChat.EVENT.KICKED_OUT, this.onKickedOut, this);

    chat.off(TencentCloudChat.EVENT.MESSAGE_READ_BY_PEER, this.onMessageReadByPeer);
    chat.on(TencentCloudChat.EVENT.MESSAGE_READ_BY_PEER, this.onMessageReadByPeer, this);

    getApp().globalData.bus.$off("NEED_UPDATE_CONVERSATION");
    getApp().globalData.bus.$on("NEED_UPDATE_CONVERSATION", function () {
      that.getConversation();
    });

    // 网络状态发生改变
    chat.off(TencentCloudChat.EVENT.NET_STATE_CHANGE, this.onNetStateChange);
    chat.on(TencentCloudChat.EVENT.NET_STATE_CHANGE, this.onNetStateChange, this);
  }

  //获取会话列表 IM
  getConversation() {
    let that = this;
    let chat = getApp().globalData.tim;

    if (!chat) {
      this.getUserInfo();
      return;
    }

    this.getConversationFromYL();
    return

    // 获取全量的会话列表
    let promise = chat.getConversationList();
    promise.then(function(imResponse) {
    // 全量的会话列表，用该列表覆盖原有的会话列表
      const conversationList = imResponse.data.conversationList;
      // 从云端同步会话列表是否完成
      const isSyncCompleted = imResponse.data.isSyncCompleted;

      if (!isSyncCompleted) {
        setTimeout(() => {
          that.getConversation();
        }, 1000);
      }
      
      that.handleConversation(conversationList);
      if (that.callback) that.callback();

    }).catch(function(imError) {
      // 获取会话列表失败的相关信息
      console.warn('getConversationList error:', imError);
    });
  }

  // 处理从一览获取的会话记录，转为腾讯云的会话记录格式
  formatConversation(conversation) {
    let list = conversation.map(item => {
      try {
        item.lastMsgBody = JSON.parse(item.lastMsgBody);
      } catch (error) {
        item.lastMsgBody = {}
      }
      try {
        item.lastMsgBody.msgBody[0].msgContent = JSON.parse(item.lastMsgBody.msgBody[0].msgContent);
      } catch (error) {
        item.lastMsgBody.msgBody[0].msgContent = {}
      }
      let time = item.lastMsgTime.replace(/-/g, '/');
      let lastTime = Math.floor(new Date(time).getTime() / 1000);

      let messageForShow = "";
      let msgContent = item.lastMsgBody.msgBody[0].msgContent;
      let msgType = item.lastMsgBody.msgBody[0].msgType;
      const msgTypeToDisplay = {
        'TIMTextElem': msgContent && msgContent.Text || '',
        'TIMImageElem': '[图片]',
        'TIMFileElem': '[文件]',
      };
      messageForShow = msgTypeToDisplay[msgType] || '';

      let obj = {
        conversationId: item.conversationId, // yl自主生成的会话id
        conversationID: "C2C"+item.targetAccount, // 腾讯云单聊会话id
        customData: '',
        lastMessage: {
          // cloudCustomData: "",
          fromAccount: item.fromAccount,
          isPeerRead: item.isRead,
          // isRevoked: false,
          // lastSequence: 1011470001,
          // lastTime: 1739239906,
          lastTime: lastTime,
          messageForShow: messageForShow,
          // nameCard: "",
          // nick: "xxx",
          // onlineOnlyFlag: false,
          payload: item.lastMsgBody.msgBody[0].msgContent,
          revoker: null,
          type: item.lastMsgBody.msgBody[0].msgType,
          version: 0,
        },
        type: "C2C",
        unreadCount: item.unReadCount,
        userProfile: {
          // adminForbidType: "AdminForbid_Type_None",
          // allowType: "AllowType_Type_AllowAny",
          avatar: httpToHttps(item.targetAccountInfo.picSrc),
          // birthday: 0,
          // gender: "",
          // language: 0,
          // lastUpdatedTime: 0,
          // level: 0,
          // location: "",
          // messageSettings: 0,
          nick: item.targetAccountInfo.nickname,
          // profileCustomField: [],
          // role: 0,
          // selfSignature: "",
          userID: item.targetAccount,
        }
      }
      return obj
    });

    return list;
  };

  // 获取会话列表 YL
  getConversationFromYL() {
    let personId = uni.getStorageSync("person-id").slice(2) || undefined;
    if (!personId) return
    let uname = personId;
    if (uni.getStorageSync("login-status") === "consultant") {
      uname += `_consultant`;
    }

    const params = {
      uname: uname
    }
    getConversationList(params).then(res => {
      if (res.code === 200) {
        const conversationList = this.formatConversation(res.data);
        
        this.handleConversation(conversationList);
        if (this.callback) this.callback();
      }
    })
  }
}
